package com.luofan.common.filter;

import com.luofan.common.util.JwtUtil;
import com.luofan.common.util.UserContext;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * JWT过滤器
 * 拦截除了 /login 外的请求，并将token中的id,role,sectionId存入TreadLocal中
 */
@Component
public class JwtAuthenticationFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取请求路径
        String uri = httpRequest.getRequestURI();
        // 排除 /login 请求
        if ("/user/login".equals(uri)) {
            chain.doFilter(request, response);
            return;
        }
        if ("/file".equals(uri)) {
            chain.doFilter(request, response);
            return;
        }
        // 排除所有文件相关请求（包含子路径）
//        if (uri.startsWith("/file") || uri.startsWith("/file/")) {
//            chain.doFilter(request, response);
//            return;
//        }

        // 从请求头中获取 Token
        String authorizationHeader = httpRequest.getHeader("Authorization");

        //判断token是否存在
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            //不存在返回401
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write("Missing Authorization header");
            return;
        }

        //去除"Bearer " 前缀
        String token = authorizationHeader.substring(7);

        try {
            //判断jwt是否过期
            if (jwtUtil.isTokenExpired(token)) {
                httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                httpResponse.getWriter().write("Token has expired");
                return;
            }

            // 提取用户信息
            Long userId = jwtUtil.extractUserId(token);
            Byte role = jwtUtil.extractRole(token);
            Long sectionId = jwtUtil.extractSectionId(token);

            // 将用户信息存入 ThreadLocal
            UserContext.setCurrentUser(userId, role, sectionId);

            // 继续执行后续逻辑
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();  // 打印异常堆栈
            // Token 无效，返回 401 未授权
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write("Invalid token: " + e.getMessage());
        } finally {
            UserContext.clear();  // 清除 ThreadLocal
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑（可选）
    }

    @Override
    public void destroy() {
        // 销毁逻辑（可选）
    }
}
